package com.link.base.wechat.devparty.controller;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.basic.util.MsgUtil;
import com.link.base.wechat.basic.util.SignUtil;
import com.link.base.wechat.thirdparty.service.WxReceiveMsgService;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.core.basic.service.ServiceException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 微信开发者模式下，消息事件接入
 *
 * @author ouyangzhenqiang
 * @date 2019/03/10 23:39
 */
@Controller
@RequestMapping("/link/wxDevParty")
public class DevPartyAuthController {
    /**
     * 应用token
     */
    private String appToken = "";
    @Resource
    private WxPlatformService wxPlatformService;
    @Resource
    private WxReceiveMsgService wxReceiveMsgService;

    /**
     * 根据公众号应用Id获取接入参数
     *
     * @author ouyangzhenqiang
     * @date 2019/03/10 23:49
     * @param authorizerAppid 授权公众号Id
     */
    private void initParam(String authorizerAppid) throws Exception {
        WxPlatform wxPlatform = wxPlatformService.getWxPlatformByAppId(authorizerAppid);
        if (wxPlatform == null) {
            throw new ServiceException("DEVPARTY-001", authorizerAppid);
        }
        String appId = wxPlatform.getWx_app_id();
        appToken = wxPlatform.getWx_app_token();
        String appEncodingAESKey = wxPlatform.getWx_encord_aes_key();
        String appSecret = wxPlatform.getWx_app_secret();
        LCLogger.info().withMessageKey("开发者模式接入").withMessage("appId => " + appId
            + "，appToken => " + appToken + "，appEncodingAESKey => " + appEncodingAESKey + "，appSerect => " + appSecret).flush();
    }

    @RequestMapping(value = "/access/{authorizerAppid}", method = { RequestMethod.GET, RequestMethod.POST })
    public void access(@PathVariable("authorizerAppid") String authorizerAppid,
                       HttpServletRequest request, HttpServletResponse response) throws Exception {
        initParam(authorizerAppid);
        // 判断访问方式
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            // 进行认证
            String msg_signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            String[] arr = new String[] { appToken, timestamp, nonce };
            Arrays.sort(arr);
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.length; i++) {
                content.append(arr[i]);
            }
            MessageDigest md;
            String tmpStr = "";
            try {
                md = MessageDigest.getInstance("SHA-1");
                byte[] digest = md.digest(content.toString().getBytes());
                tmpStr = SignUtil.byteToStr(digest);
            } catch (NoSuchAlgorithmException e) {
                LCLogger.withException(e);
            }
            try {
                if (tmpStr != null) {
                    if (tmpStr.equals(msg_signature.toUpperCase())) {
                        response.getWriter().write(echostr.toString());
                    }
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        } else {
            try {
                // 转码UTF-8,防止乱码
                request.setCharacterEncoding("utf-8");
                response.setCharacterEncoding("utf-8");
                // 提取文件流
                String encXml = MsgUtil.getRequestStr(request);
                /**
                 * 将解密后的明文发送至需要的服务器
                 * 不需等待具体处理结果，直接返回success给微信服务器
                 */
                JSONObject obj = new JSONObject();
                obj.put("xmlMsg", encXml);
                obj.put("authorizer_appid", authorizerAppid);
                wxReceiveMsgService.receiveMsgBroadcast(obj.toJSONString());
                String sendData = "success";
                response.getWriter().write(sendData);
            } catch (IOException e) {
                LCLogger.withException(e);
                // 无论如何至少需要回复success
                String sendData = "success";
                response.getWriter().write(sendData);
            }
        }
    }
}
